import { history } from '@/router';
import { getUserInfo } from '@/services/global';
import useMenuStore from '@/store/menu';
import useUserStore from '@/store/user';
import { ConfigProvider, Spin } from 'antd';
import locale from 'antd/es/locale/zh_CN';
import 'moment/dist/locale/zh-cn';
import type { FC } from 'react';
import { useState } from 'react';
// moment.locale('zh-cn');
/**
 * 验证 用户登录状态
 * @returns {boolean} token是否有效
 */
async function validToken(): Promise<boolean> {
  const { token } = useUserStore.getState();
  const hasToken = Boolean(token);
  if (!hasToken) return false;
  const { ok, data } = await getUserInfo();
  if (ok) {
    useMenuStore.getState().setPermissions(data.userPermissions);
    useUserStore.getState().setUser(data);
  }
  return ok;
}
const filterUrl = ['/logout', '/redirect', '/login'];

let isRender = false;
const BasicLayout: FC = (props) => {
  const [loading, setLoading] = useState(!isRender);
  if (isRender === false) {
    const { pathname } = history.location;
    validToken().then((ok) => {
      if (ok) {
        if (pathname === '/login') {
          history.replace('/');
        }
      } else if (pathname !== '/login') {
        history.replace(`/logout?redirect=${filterUrl.includes(pathname) ? '/' : pathname}`);
      } else {
        //
      }
      setLoading(false);
    });
    isRender = true;
  }

  return (
    <ConfigProvider locale={locale} componentSize='middle' input={{ autoComplete: 'off' }}>
      {loading ? (
        <div
          style={{
            height: '100vh',
            textAlign: 'center',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          <div style={{ fontSize: 32, marginBottom: '10vh' }}>气象雷达预测评估平台</div>
          <Spin size='large' tip='页面加载中' />
        </div>
      ) : (
        props.children
      )}
    </ConfigProvider>
  );
};

export default BasicLayout;
